package com.zy.qudadid.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.rey.material.app.Dialog;
import com.rey.material.widget.Button;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zy.lcpassenger.R;
import com.zy.qudadid.model.Stroke;
import com.zy.qudadid.model.StrokeInfor;
import com.zy.qudadid.model.Travel;
import com.zy.qudadid.network.Const;
import com.zy.qudadid.presenter.IndexFormPresenter;
import com.zy.qudadid.ui.activity.base.ToolBarActivity;
import com.zy.qudadid.ui.view.IndexFormView;
import com.zy.qudadid.ui.widget.TwoButtonDialog;
import com.zy.qudadid.utils.AESCrypt;
import com.zy.qudadid.utils.Bun;
import com.zy.qudadid.utils.StringUtil;
import com.zy.qudadid.utils.UserUtil;
import com.zy.util.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by ninos on 2016/7/30.
 */
public class IndexFormActivity extends ToolBarActivity<IndexFormPresenter> implements IndexFormView {

    Button dc_yes;
    Button dc_no;
    TextView dc_phone;
    @Bind(R.id.if_isshow)
    LinearLayout if_isshow;
    @Bind(R.id.if_start)
    TextView ifStart;
    @Bind(R.id.if_end)
    TextView ifEnd;
    @Bind(R.id.if_phone)
    ImageView ifPhone;
    @Bind(R.id.if_state)
    TextView ifState;
    @Bind(R.id.if_money)
    TextView ifMoney;
    @Bind(R.id.starbar)
    RatingBar starbar;
    @Bind(R.id.txtTip)
    TextView txtTip;
    @Bind(R.id.hujiaocar)
    android.widget.Button hujiaocar;
    @Bind(R.id.llTip)
    LinearLayout llTip;
    private Dialog dc_dialog;
    private View dc_view;
    private String phone = "18888888888";
    private StrokeInfor stroke;
    String did="";

    @Bind(R.id.if_payuser)
    Button if_payuser;
//    @Bind(R.id.if_payme)
//    Button if_payme;

    private View view;
    private LinearLayout dg_dongtai;
    private LinearLayout dg_shipin;
    private Dialog dialog;


    @OnClick(R.id.if_payuser)
    public void if_payuser() {
        Map map = new HashMap();
        map.put("order_id", stroke.id);
        map.put("golds", starbar.getRating());
        map.put("content", "");
        String json = StringUtil.toJson(map);
        try {
            String data = AESCrypt.getInstance().encrypt(json);
            presenter.postcomment(StringUtil.replaceBlank(data));
        } catch (Exception ex) {
        }
//        Map map = new HashMap();
//        map.put("orderid", stroke.id);
//        map.put("state", "3");
//        String json = StringUtil.toJson(map);
//        try {
//            String data = AESCrypt.getInstance().encrypt(json);
//            presenter.changeOrderstate(StringUtil.replaceBlank(data));
//        } catch (Exception ex) {
//        }
    }

    @Override
    protected void action() {
        showDialogMore();
    }

    @Override
    public boolean canAction() {
        return true;
    }
//    @OnClick(R.id.if_payme)
//    public void if_payme() {
//        startActivity(IndexPayMeActivity.class);
//        ActivityUtil.addActivity(this);
//    }

    @Override
    protected CharSequence provideTitle() {
        return "订单详情";
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_index_form;
    }

    @Override
    protected void initThings(Bundle savedInstanceState) {
        super.initThings(savedInstanceState);
        tvAction.setText("更多");
        dc_view = getLayoutInflater().inflate(R.layout.dialog_callphone, null);
        dc_yes = (Button) dc_view.findViewById(R.id.dc_yes);
        dc_no = (Button) dc_view.findViewById(R.id.dc_no);
        dc_phone = (TextView) dc_view.findViewById(R.id.dc_phone);
        stroke = (StrokeInfor) getIntent().getBundleExtra("data").getSerializable("stroke");

        this.view = getLayoutInflater().inflate(R.layout.dialog_dongtai, null);
        dg_dongtai = (LinearLayout) this.view.findViewById(R.id.dg_dongtai);
        dg_shipin = (LinearLayout) this.view.findViewById(R.id.dg_shipin);

        if(stroke.state.equals("1")){
            hujiaocar.setVisibility(View.VISIBLE);
            hujiaocar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(hujiaocar.getText().equals("我已上车")){
                        final TwoButtonDialog dialog = new TwoButtonDialog(getContext());
                        dialog.setConfirmText("我已上车");
                        dialog.setCancelText("我还没上车");
                        dialog.setText("您确定已上车，将开始计费？");
                        dialog.txt_queding.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                Map<String,String> map = new HashMap<String, String>();
                                map.put("order_id",stroke.id);
                                map.put("user_id",new UserUtil(getContext()).getUserId());
                                map.put("queren",1+"");
                                String json = JsonUtils.toJson(map);

                                AESCrypt aesCrypt = null;
                                try {
                                    aesCrypt = new AESCrypt();
                                    String d = StringUtil.replaceBlank(aesCrypt.encrypt(json));

                                    OkHttpUtils.post()
                                            .url(Const.BASE_URL+"api.php/Order/passengerOn_car")
                                            .addParams("args", d)
                                            .build()
                                            .execute(new StringCallback() {
                                                @Override
                                                public void onError(Call call, Exception e, int i) {

                                                }

                                                @Override
                                                public void onResponse(String response, int i) {
                                                    JSONObject json;
                                                    try {
                                                        json = new JSONObject(response);
                                                        int code = json.getInt("code");
                                                        if(code == 200){
                                                            Toast.makeText(getContext(),"已确认上车",Toast.LENGTH_SHORT).show();
                                                            hujiaocar.setText("等待司机结算");
                                                            MainActivity.rentState = 2;
                                                            Const.downTag = 1;
                                                        }
                                                    } catch (JSONException e) {
                                                        e.printStackTrace();
                                                    }
                                                }
                                            });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }
                        });
                    }
                }
            });
        }else{
            hujiaocar.setVisibility(View.GONE);
        }

        Map map = new HashMap();
        map.put("order_id", stroke.id);
        map.put("type",1+"");
        map.put("user_id",new UserUtil(getContext()).getUserId());
        String json = StringUtil.toJson(map);
        try {
            String data = AESCrypt.getInstance().encrypt(json);
            String d = StringUtil.replaceBlank(data);

            presenter.passengerOrder(d);
        } catch (Exception ex) {
        }
    }

    @Override
    public void initListeners() {
        //拨打乘客电话
        dc_yes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent it = new Intent();
                    it.setAction(Intent.ACTION_CALL);
                    it.setData(Uri.parse("tel:" + phone));
                    startActivity(it);
//                startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone)));
                    dc_dialog.dismiss();
                }catch (Exception e){
                    toast("请开启拨打电话权限");
                }
            }
        });

        dc_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dc_dialog.dismiss();
            }
        });

        dg_dongtai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent;
                try {
                    intent = new Intent();
                    intent.setData(Uri.parse("tel:" + new UserUtil(IndexFormActivity.this).getSharedPreferences("servicephone")));
                    intent.setAction(Intent.ACTION_CALL);
                    startActivity(intent);
                }catch (Exception e){
                    Toast.makeText(getContext(),"请开启拨打电话权限",Toast.LENGTH_SHORT).show();
                }

            }
        });

        dg_shipin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(OwnYijianActivity.class, new Bun().putString("did",did).putString("name",driverName).putString("mobile",phone).putString("orderid",orderId).putString("avatar",avatar).ok());
                dialog.dismiss();
            }
        });
    }

    @Override
    public IndexFormPresenter createPresenter() {
        return new IndexFormPresenter();
    }

    private void showDialogCallPhone() {
        if (dc_dialog == null)
            dc_dialog = new Dialog(this).backgroundColor(Color.parseColor("#ffffff")).contentView(dc_view);
        dc_dialog.show();
    }

    @OnClick(R.id.if_phone)
    public void onClick() {
        showDialogCallPhone();
    }

    private String driverName="";
    private String orderId="";
    private String avatar="";

    @Override
    public void success(Travel travel) {
        did = travel.driver_user_id;
        orderId = travel.id;
        ifStart.setText(travel.departure);
        ifEnd.setText(travel.destination);
        ifState.setText(getStrokeState(travel.state));
        ifMoney.setText(travel.price);
        dc_phone.setText("电话："+travel.driver.driver_mobile);
        phone = travel.driver_mobile;
        driverName = travel.driver_realname;
        avatar = travel.avatar;
        if(Double.parseDouble(travel.tip)>0){
            llTip.setVisibility(View.VISIBLE);
            txtTip.setText(travel.tip);
        }else{
            llTip.setVisibility(View.GONE);
        }
//        if(travel.state.equals("5")){
//            if_isshow.setVisibility(View.VISIBLE);
//        }else{
//            if_isshow.setVisibility(View.VISIBLE);
//        }

        if(travel.comment_star.equals("-1")){
            if_isshow.setVisibility(View.VISIBLE);
            starbar.setVisibility(View.VISIBLE);
        }else{
            if_isshow.setVisibility(View.GONE);
            starbar.setVisibility(View.GONE);
        }
    }

    public String getStrokeState(String state){
//        state0,1,2,3,4,5分别表示：叫车发布成功-----已接单啦，等待司机到来-----行驶中-----已完成的叫车列表-----已取消的叫车列表-----未支付订单
        String s = "无状态";
        switch (state){
            case "0":
                s = "等待中";
                break;
            case "1":
                s = "已接单";
                break;
            case "2":
                s = "行驶中";
                break;
            case "3":
                s = "已完成";
                break;
            case "4":
                s = "已取消";
                break;
            case "5":
                s = "未支付";
                break;
            case "7":
                s = "等待司机确认";
                break;
        }
        return s;
    }

    @Override
    public void error() {
        toast("订单获取失败");
    }

    @Override
    public void successstate() {
        toast("订单已完成");
//        ActivityUtil.finishActivitys();
//        finish();
    }

    @Override
    public void errorstate() {

    }

    @Override
    public void successp() {
        toast("评价成功");
        if_isshow.setVisibility(View.GONE);
        starbar.setVisibility(View.GONE);
    }

    @Override
    public void errorp() {

    }

    private void showDialogMore() {
        if (dialog == null)
            dialog = new Dialog(getContext()).backgroundColor(Color.parseColor("#ffffff")).contentView(view);
        dialog.show();
    }
}
